package com.wqj.ride.happyriding.nav.activity;

import android.annotation.SuppressLint;
import android.app.ActivityOptions;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewAnimator;

import com.amap.api.location.AMapLocation;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.Poi;
import com.amap.api.navi.enums.NaviType;
import com.amap.api.navi.model.AMapNaviPath;
import com.amap.api.navi.model.NaviLatLng;
import com.amap.api.navi.view.PoiInputItemWidget;
import com.amap.api.navi.view.RouteOverLay;
import com.wqj.ride.happyriding.R;
import com.wqj.ride.happyriding.base.BaseTransitionInActivity;
import com.wqj.ride.happyriding.base.BaseNavActivity;
import com.wqj.ride.happyriding.bluetooth.bt.BtDevicesActivity;
import com.wqj.ride.happyriding.location.MyLocationManager;
import com.wqj.ride.happyriding.location.OnLocationListener;
import com.wqj.ride.happyriding.utils.Constants;
import com.wqj.ride.happyriding.utils.ToastUtil;

public class RouteShowActivity extends BaseNavActivity
        implements View.OnClickListener, AMap.OnCameraChangeListener {
    private static int REQUEST_GPS_CODE = 887;
    //private boolean congestion, cost, hightspeed, avoidhightspeed;
    /**
     * 导航对象(单例)
     */
    private AMap mAmap;
    /**
     * 地图对象
     */
    private MapView mRouteMapView;
    private Marker mStartMarker;
    private Marker mEndMarker;
    private NaviLatLng endLatlng; //= new NaviLatLng(39.955846, 116.352765);
    private NaviLatLng startLatlng; // = new NaviLatLng(39.925041, 116.437901);
    /**
     * 保存当前算好的路线
     */
    private SparseArray<RouteOverLay> routeOverlays = new SparseArray<RouteOverLay>();

    /**
     * 当前用户选中的路线，在下个页面进行导航
     */
    private int routeIndex = 0;
    /**
     * 路线的权值，重合路线情况下，权值高的路线会覆盖权值低的路线
     **/
    private int zindex = 1;
    /**
     * 路线计算成功标志位
     */
    // 动态创建的pass point的index
    private int passPointIndex = 0;
    private TextView[] passPointViewList = new TextView[8];
    private NaviLatLng[] passPointLatLngList = new NaviLatLng[8];

    private boolean calculateSuccess = false;

    private Double currentLat = Double.NaN;
    private Double ccurrentLng = Double.NaN;
    private String  city = "";

    private TextView ePointView;

    private LinearLayout mEndPosLayout;

    private LinearLayout mOptionOne;

    private TextView mTvTimeOne;
    private TextView mTvDisOne;
    private TextView mTvLabelOne;

    private ViewAnimator mSwitcher;

    private Button mStartNavi;
    private Button mStartEmulatorNavi;

    private Handler mHandler;

    RelativeLayout mResultLalyout;

    RelativeLayout mHeaderLayout;

    private Boolean isCalculated = false;
    private Object routeCalculateLock = new Object();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_route_show);

        initView();
        mRouteMapView.onCreate(savedInstanceState);
        initData();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mRouteMapView.onResume();

        enableGps();

        if (null != endLatlng) {
            calculateRoute();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        mRouteMapView.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        mResultLalyout.setVisibility(View.GONE);

        mRouteMapView.onDestroy();
    }

    private void enableGps() {
        boolean isGpsEnabled = MyLocationManager
                .getInstance(getApplicationContext())
                .isGPSEnabled();

        Log.d("wqj", "gps enabled: " + isGpsEnabled);
        if (!isGpsEnabled) {
            new AlertDialog.Builder(this)
                    .setIcon(android.R.drawable.ic_dialog_info)
                    .setTitle("定位模式")
                    .setMessage("请打开高精度定位")
                    // .setNegativeButton("取消", null)
                    .setPositiveButton("打开", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivityForResult(intent, REQUEST_GPS_CODE);
                            dialogInterface.dismiss();
                        }
                    })
                    .show();
            Log.d("wqj", "need open gps");
        }
    }

    private void initMapUI(UiSettings settings) {
        settings.setZoomControlsEnabled(false);
        settings.setAllGesturesEnabled(true);
    }

    private void initView() {
        mResultLalyout = (RelativeLayout) findViewById(R.id.id_rl_navi);
        mHeaderLayout = (RelativeLayout) findViewById(R.id.id_layout_header);
        mHandler = new Handler();

        mRouteMapView = (MapView) findViewById(R.id.mapView);

        mStartNavi = (Button) findViewById(R.id.id_btn_startNavi);
        mStartNavi.setOnClickListener(this);

        mStartEmulatorNavi = (Button) findViewById(R.id.id_btn_startEmulatorNavi);
        mStartEmulatorNavi.setOnClickListener(this);


        mEndPosLayout = (LinearLayout) findViewById(R.id.endPosLayout);

        mOptionOne = (LinearLayout) findViewById(R.id.id_ll_optionOne);
        mOptionOne.setOnClickListener(this);

        ePointView = (TextView) findViewById(R.id.ePointView);
        ePointView.setOnClickListener(this);

        mTvTimeOne = (TextView) findViewById(R.id.id_tv_time_optOne);
        mTvDisOne = (TextView) findViewById(R.id.id_tv_distance_optOne);
        mTvLabelOne = (TextView) findViewById(R.id.id_tv_label_optOne);

        mSwitcher = (ViewAnimator) findViewById(R.id.id_va_pageSwitcher);
    }

    private void initUI() {
        initMapUI(mAmap.getUiSettings());
        mSwitcher.setDisplayedChild(1);

        LatLng latLng = new LatLng(currentLat,ccurrentLng);
        final Marker marker = mAmap.addMarker(new MarkerOptions().position(latLng));
                // .title(WeatherManager.getInstance().getLocation().getCity())
                // .snippet(WeatherManager.getInstance().getLocation().getDistrict()));

        // mAmap.moveCamera(CameraUpdateFactory.changeLatLng(latLng));
        mAmap.moveCamera(CameraUpdateFactory
                .newCameraPosition(new CameraPosition(latLng, 16, 0, 0)));

    }

    private void initData() {
        mAmap = mRouteMapView.getMap();

        mStartMarker = mAmap.addMarker(new MarkerOptions()
                .icon(BitmapDescriptorFactory
                        .fromBitmap(BitmapFactory.decodeResource(getResources()
                                , R.drawable.start_point))));
        mEndMarker = mAmap.addMarker(new MarkerOptions().icon(BitmapDescriptorFactory
                .fromBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.end_point))));

        // AMapLocation location = WeatherManager.getInstance().getLocation();
        MyLocationManager.getInstance(getApplicationContext())
                .getCurrentLocation(new OnLocationListener() {
            @Override
            public void onLocationUpdate(AMapLocation location) {
                currentLat = location.getLatitude();//获取纬度
                ccurrentLng = location.getLongitude();//获取经度
                startLatlng = new NaviLatLng(currentLat, ccurrentLng);
                city = location.getCity();
                mStartMarker.setPosition(new LatLng(currentLat, ccurrentLng));
                initUI();
            }
        });
    }

    private void initListener() {

    }


    private void calculateRoute() {
        mSwitcher.setDisplayedChild(1);
        clearRoute();
        routeOverlays.clear();
        // 没有设置途经点
        if (0 == passPointIndex) {
            Log.d("wqj", "index 0 start: " + startLatlng + ", end: " + endLatlng);
            // mAMapNavi.calculateRideRoute(startLatlng, endLatlng);
            mAMapNavi.calculateRideRoute(endLatlng);
        } else {
            new Thread(new Runnable() {
                public void run() {
                    for (int i = 0; i <= passPointIndex; i++) {
                        // 有途经点时顺序调用onCalculateRideRouteSuccess后再调用calcRideRoute函数
                        if (i == 0) {
                            // 计算起点到第一个途经点
                            mAMapNavi.calculateRideRoute(startLatlng, passPointLatLngList[i]);
                        } else if (i < passPointIndex) {
                            // 计算前一个途经点到下一个途经点
                            synchronized(routeCalculateLock) {
                                if (!isCalculated) {
                                    try {
                                        routeCalculateLock.wait();
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                } else {
                                    mAMapNavi.calculateRideRoute(passPointLatLngList[i - 1]
                                            , passPointLatLngList[i]);
                                    isCalculated = false;
                                }
                            }
                        } else if (i == passPointIndex) {
                            // 计算最后一个途经点到终点
                            synchronized(routeCalculateLock) {
                                if (!isCalculated) {
                                    try {
                                        routeCalculateLock.wait();
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                } else {
                                    mAMapNavi.calculateRideRoute(passPointLatLngList[i - 1]
                                            , endLatlng);
                                    isCalculated = false;
                                }
                            }
                        }
                        }

                }
            }).start();
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public void onBackClick(View view) {
        this.finishAfterTransition();
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @SuppressLint("RestrictedApi")
    private void startActivityWithOptions(Intent intent, int requestCode) {
        ActivityOptions transitionActivity =
                ActivityOptions.makeSceneTransitionAnimation(this);
        startActivityForResult(intent, requestCode, transitionActivity.toBundle());
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mRouteMapView.onSaveInstanceState(outState);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.ePointView:
                intent = new Intent(this, SearchActivity.class);
                intent.putExtra(BaseTransitionInActivity.EXTRA_TRANSITION
                        , BaseTransitionInActivity.TRANSITION_FADE_FAST);
                intent.putExtra(Constants.EXTRA_CURRENT_CITY, city);
                intent.putExtra(Constants.EXTRA_HINT, "输入终点");
                intent.putExtra(Constants.EXTRA_POINTTYPE, PoiInputItemWidget.TYPE_DEST);
                startActivityWithOptions(intent, Constants.SEARCH_END_REQUEST_CODE);
                break;

            case R.id.id_ll_optionOne:
                routeIndex = 0;
                changeRoute();
                break;

            case R.id.id_ib_showPreference:
                intent = new Intent(this, BtDevicesActivity.class);
                startActivity(intent);
                break;

            case R.id.id_btn_startNavi:
                intent = new Intent(getApplicationContext()
                        , CustomRouteNaviActivity.class);
                intent.putExtra("NaviType", NaviType.GPS);
                intent.putExtra("Destination", ePointView.getText());
                startActivity(intent);
                finish();
                break;

            case R.id.id_btn_startEmulatorNavi:
                intent = new Intent(getApplicationContext()
                        , CustomRouteNaviActivity.class);
                intent.putExtra("NaviType", NaviType.EMULATOR);
                intent.putExtra("Destination", ePointView.getText());
                startActivity(intent);
                finish();
                break;

            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Constants.SEARCH_LOCATION_RESULT_CODE) {

            Poi poi = data.getParcelableExtra(Constants.EXTRA_POI);

            if (requestCode == Constants.SEARCH_END_REQUEST_CODE) {
                if (poi != null) {
                    ePointView.setText(poi.getName());
                    endLatlng = new NaviLatLng(poi.getCoordinate().latitude
                            , poi.getCoordinate().longitude);
                    mEndMarker.setPosition(new LatLng(poi.getCoordinate().latitude
                            , poi.getCoordinate().longitude));
                }
            }
            // 途经点的八个request code, 画出途经点
            else if ((requestCode >= Constants.SEARCH_PASS_REQUEST_CODE0)
                    && (requestCode <= Constants.SEARCH_PASS_REQUEST_CODE7)) {
                int index = requestCode - Constants.SEARCH_PASS_REQUEST_CODE0;
                Log.d("wqj", "add pass point: " + index);
                Log.d("wqj", "add pass point: " + passPointViewList[index]);

                if (poi != null) {
                    passPointViewList[index].setText(poi.getName());
                    passPointLatLngList[index] = new NaviLatLng(poi.getCoordinate().latitude
                            , poi.getCoordinate().longitude);
                    Marker passMarker = mAmap.addMarker(new MarkerOptions()
                            .icon(BitmapDescriptorFactory
                            .fromBitmap(BitmapFactory.decodeResource(getResources()
                                    , R.drawable.amap_through))));
                    passMarker.setPosition(new LatLng(poi.getCoordinate().latitude
                            , poi.getCoordinate().longitude));
                }
            }
        }
        else if (REQUEST_GPS_CODE == requestCode) {

        }
    }

    @Override
    public void onCalculateRouteFailure(int i) {
        calculateSuccess = false;
        synchronized(routeCalculateLock) {
            isCalculated = true;
            routeCalculateLock.notify();
        }
        ToastUtil.showerror(getApplicationContext(), i);
    }

    @Override
    public void onCalculateRouteSuccess(int[] ints) {
        Log.d("wqj", "calc route success: " + ints.length);
        routeIndex = 0;
        if (passPointIndex != 0) {
            synchronized (routeCalculateLock) {
                isCalculated = true;
                routeCalculateLock.notify();
            }
        }
        Log.d("wqj", "calc route success: " + ints.length);

        mResultLalyout.setVisibility(View.VISIBLE);

        mOptionOne.setVisibility(View.VISIBLE);
        // 单路径用getNaviPath， 多路径用getNaviPaths
        AMapNaviPath path = mAMapNavi.getNaviPath();
        Log.d("wqj", "path: " + path);
        if (path != null) {
            drawRoutes(ints[0], path);

            double second = path.getAllTime();
            long min = Math.round( second / 60);

            int distance = path.getAllLength();
            String disLabel = "";
            if (distance > 1000) {
                double km = (double)distance / 1000;
                km = (double) Math.round(km * 10) / 10;
                disLabel = km + "公里";
            } else {
                disLabel = distance + "米";
            }
            mTvTimeOne.setText("总耗时: " + min + "分钟");
            mTvDisOne.setText("总里程: " + disLabel);
            mTvLabelOne.setText("我的位置 -> " + ePointView.getText());
        }

        changeRoute(); //
    }

    private void drawRoutes(int routeId, AMapNaviPath path) {
        calculateSuccess = true;
        mAmap.moveCamera(CameraUpdateFactory.changeTilt(0));
        RouteOverLay routeOverLay = new RouteOverLay(mAmap, path, this);
        routeOverLay.setTrafficLine(true);
        routeOverLay.setStartPointBitmap(BitmapFactory.decodeResource(getResources()
                , R.drawable.marker_blue));
        routeOverLay.setEndPointBitmap(BitmapFactory.decodeResource(getResources()
                , R.drawable.marker_blue));
        routeOverLay.addToMap();
        routeOverlays.put(routeId, routeOverLay);

    }

    public void changeRoute() {
        if (!calculateSuccess) {
            Toast.makeText(this, "请先算路", Toast.LENGTH_SHORT).show();
            return;
        }

        if (routeIndex >= routeOverlays.size())
            routeIndex = 0;
        int routeID = routeOverlays.keyAt(routeIndex);
        //突出选择的那条路
        for (int i = 0; i < routeOverlays.size(); i++) {
            int key = routeOverlays.keyAt(i);
            routeOverlays.get(key).setTransparency(0.4f);
        }
        routeOverlays.get(routeID).setTransparency(1);
        routeOverlays.get(routeID).zoomToSpan(400);
        /**把用户选择的那条路的权值弄高，使路线高亮显示的同时，重合路段不会变的透明**/
        routeOverlays.get(routeID).setZindex(zindex++);

        //必须告诉AMapNavi 你最后选择的哪条路
        mAMapNavi.selectRouteId(routeID);

        // highlightView();
    }

    /*
    private void highlightView() {
        LinearLayout parent = (LinearLayout) findViewById(R.id.id_ll_selection);

        int children = parent.getChildCount();

        for (int i = 0; i < children; i++) {

            LinearLayout child = (LinearLayout) parent.getChildAt(i);

            if (routeIndex == i) {
                child.setBackgroundColor(Color.LTGRAY);

                int count = child.getChildCount();

                for (int j = 0; j < count; j++) {
                    TextView tv = (TextView) child.getChildAt(j);
                    tv.setTextColor(Color.parseColor("#3399dd"));
                }

            } else {
                child.setBackgroundColor(Color.WHITE);

                int count = child.getChildCount();

                for (int j = 0; j < count; j++) {
                    TextView tv = (TextView) child.getChildAt(j);
                    tv.setTextColor(Color.parseColor("#797979"));
                }
            }
        }
    }
    */

    /**
     * 清除当前地图上算好的路线
     */
    private void clearRoute() {
        for (int i = 0; i < routeOverlays.size(); i++) {
            RouteOverLay routeOverlay = routeOverlays.valueAt(i);
            routeOverlay.removeFromMap();
        }
        routeOverlays.clear();
    }

    @Override
    public void onCameraChange(CameraPosition cameraPosition) {

    }

    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {

    }
}
